﻿using System;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlClient;

namespace WebDiagnostics.Diagnosers.DatabaseConnectivity
{
    public class SqlConnectionStringQuery : DatabaseQuery
    {
        public string ConnectionString { get; set; }
        public string QueryCommand { get; set; }

        public SqlConnectionStringQuery(ConnectionStringSettings connectionString)
            : base(connectionString.Name)
        {
            ConnectionString = connectionString.ConnectionString;
        }

        public override DatabaseQueryResult Execute()
        {
            DatabaseQueryResultKind result;
            string message = null;

            try
            {
                using (var connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();

                    if (!string.IsNullOrWhiteSpace(QueryCommand))
                        return ExecuteQueryCommand(connection);
                    else
                        result = DatabaseQueryResultKind.Succeeded;
                }
            }
            catch (Exception e)
            {
                message = e.ToString();
                result = DatabaseQueryResultKind.Failed;
            }

            return new DatabaseQueryResult(Name, result, message);
        }

        private DatabaseQueryResult ExecuteQueryCommand(SqlConnection connection)
        {
            using (DbCommand command = new SqlCommand(QueryCommand, connection))
            {
                int commandResult = command.ExecuteNonQuery();
                bool commandSucceeded = commandResult > -1;

                var result = commandSucceeded
                                 ? DatabaseQueryResultKind.Succeeded
                                 : DatabaseQueryResultKind.Failed;

                string message = string.Format("Command result: {0}", commandResult);

                return new DatabaseQueryResult(Name, result, message);
            }
        }
    }
}